﻿#include "musicconfig.h"
#include "ui_musicconfig.h"

MusicConfig::MusicConfig(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::MusicConfig)
{
    ui->setupUi(this);

    setWindowTitle(QStringLiteral("音乐设置"));


    timer = new QTimer(this);
    timer->start(1000);


    ui->currVoice->setText(QStringLiteral("当前音量：") + QString::number(Global::currVoice) + "%");

    if(Global::player && (Global::player->state() == QMediaPlayer::PlayingState || Global::player->state() == QMediaPlayer::PausedState))
        ui->currState->setText(QStringLiteral("正在播放")), ui->currMusic->setText(Global::currMusic);
    else ui->currState->setText(QStringLiteral("当前未播放")), ui->currMusic->setText("");

    player = new QMediaPlayer();


    musicState = "单次播放";

    bool findConfig = false;

    musicPath = QString(QDir::currentPath() + "/sounds/");


    QFile file(QDir::currentPath() + "/PMS_data/path.corgi");

    if(file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QTextStream in(&file);
        QString line = in.readLine();




        while(!line.isNull()) {

            QStringList strList = line.split("->");



            if(strList[0] == "Music_Path" && strList[1] != "PMS_None") findConfig = true, musicPath = strList[1] + "/";
            else if(strList[0] == "Music_State" && strList[1] != "PMS_None") musicState = strList[1], ui->btn_mode->setText(musicState);



            line = in.readLine();



        }

        file.close();



    }


    QDir dir;

    if(findConfig) dir = QDir(musicPath);
    else dir = QDir(QDir::currentPath() + QString("/sounds"));








    QStringList strFileList, strNameList;

    QStringList filters;

    filters << QString("*.mp3");

    dir.setNameFilters(filters);

    QDirIterator iter(dir, QDirIterator::Subdirectories);

    while(iter.hasNext()) {

        iter.next();

        QFileInfo info = iter.fileInfo();

        if(info.isFile()) strFileList.append(info.absoluteFilePath()), strNameList.append(info.baseName());


    }


    ui->listWidget->clear();



    for(auto it = strNameList.begin(); it != strNameList.end(); ++it) {
        ui->listWidget->addItem(*it), currMusicArray.push_back(*it);

    }


    connect(timer, SIGNAL(timeout()), this, SLOT(judgeState_slot()));




    connect(ui->listWidget, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(btn_play_slot()));




    connect(ui->btn_play, SIGNAL(clicked(bool)), this, SLOT(btn_play_slot()));
    connect(ui->btn_pause, SIGNAL(clicked(bool)), this, SLOT(btn_pause_slot()));
    connect(ui->btn_volplus, SIGNAL(clicked(bool)), this, SLOT(btn_volplus_slot()));
    connect(ui->btn_voldec, SIGNAL(clicked(bool)), this, SLOT(btn_voldec_slot()));
    connect(ui->btn_setPath, SIGNAL(clicked(bool)), this, SLOT(btn_setPath_slot()));
    connect(ui->btn_mode, SIGNAL(clicked(bool)), this, SLOT(btn_mode_slot()));


}


void MusicConfig::judgeState_slot() {



//    if(!ui->listWidget->hasFocus()) ui->listWidget->setFocus();



    if(Global::player && Global::player->state() == QMediaPlayer::StoppedState
            && QString::compare(ui->currState->text(), QStringLiteral("当前未播放"))) {
        if(!QString::compare(musicState, QStringLiteral("单曲循环"))) Global::player->play();
        else if(!QString::compare(musicState, QStringLiteral("随机播放"))) {


            int idx = -1;


            qDebug() << currMusicArray.length();

//            qsrand(QTime(0, 0, 0).secsTo(QTime::currentTime()));

            do {

                idx = QRandomGenerator::global()->bounded(currMusicArray.length());
//                idx = (idx * idx + 6 * idx + 1) % currMusicArray.length();
            } while(!QString::compare(currMusicArray[idx], Global::currMusic));


            qDebug() << Global::currMusic;
            qDebug() << currMusicArray[idx];







            player->setMedia(QUrl::fromLocalFile(musicPath + currMusicArray[idx] + ".mp3"));
            player->setVolume(Global::currVoice); //0~100音量范围,默认是100
            player->play();

            Global::player = player;
            Global::currMusic = currMusicArray[idx];


            ui->currMusic->setText(Global::currMusic);

            //ui->listWidget->clearSelection();

            int row = 0;
            QString strMusic;

            while(row < ui->listWidget->count()) {
                strMusic = ui->listWidget->item(row)->text();
                if(!QString::compare(strMusic, Global::currMusic)) {
                    ui->listWidget->item(row)->setSelected(true);

                    break;
                }

                ++ row;

            }











        }
        else ui->currState->setText(QStringLiteral("当前未播放")), ui->currMusic->setText("");
    }



}


void MusicConfig::btn_play_slot() {


//    这里记得改成用selected状态判定暂停重新播放
//    int row = 0;
//    QString strMusic;

//    while(row < ui->listWidget->count()) {
//        strMusic = ui->listWidget->item(row)->text();
//        if(!QString::compare(strMusic, Global::currMusic)) {
//            ui->listWidget->item(row)->setSelected(true);

//            break;
//        }

//        ++ row;

//    }










    auto item = ui->listWidget->currentItem();


    if(!item) return;

    QString txt = item->text();

    if(!txt.length()) return;


    qDebug() << "--->" << txt;




    if(Global::player && Global::player->state() == QMediaPlayer::PlayingState) {

        if(QString::compare(txt, Global::currMusic)) Global::player->stop();

        else return;

    }


    if(Global::player && Global::player->state() == QMediaPlayer::PausedState) {

        if(QString::compare(txt, Global::currMusic)) Global::player->stop();

        else {
            Global::player->play();
            return;
        }




    }

    player->setMedia(QUrl::fromLocalFile(musicPath + txt + ".mp3"));
    player->setVolume(Global::currVoice); //0~100音量范围,默认是100
    player->play();




    qDebug() << QThread::currentThreadId();
    qDebug() << player;

    Global::player = player;
    Global::currMusic = txt;

    ui->currState->setText(QStringLiteral("正在播放"));
    ui->currMusic->setText(Global::currMusic);

}

void MusicConfig::btn_pause_slot() {



//    QListWidgetItem* item = nullptr;
//    for(int i = 0; i < ui->listWidget->count(); ++i)
//        if(ui->listWidget->item(i)->isSelected()){
//            item = ui->listWidget->item(i);
//            break;
//        }


//    if(!item) return;

//    QString txt = item->text();

//    if(!txt.length()) return;


//    qDebug() << "this" << txt;



    if(Global::player && Global::player->state() == QMediaPlayer::PlayingState) {



        //if(!QString::compare(txt, Global::currMusic))
            Global::player->pause(), qDebug() << 1;


    }

}

void MusicConfig::btn_volplus_slot() {
    Global::currVoice += 10;
    if(Global::currVoice > 100) Global::currVoice = 100;

    ui->currVoice->setText(QStringLiteral("当前音量：") + QString::number(Global::currVoice) + "%");

    if(Global::player) Global::player->setVolume(Global::currVoice);
}


void MusicConfig::btn_voldec_slot() {
    Global::currVoice -= 10;
    if(Global::currVoice < 0) Global::currVoice = 0;

    ui->currVoice->setText(QStringLiteral("当前音量：") + QString::number(Global::currVoice) + "%");

    if(Global::player) Global::player->setVolume(Global::currVoice);
}

void MusicConfig::btn_setPath_slot() {

    QString pathName;

//    pathName = QFileDialog::getOpenFileName(this, QStringLiteral("选择程序"),
//                                            "D:/", tr("Exe files(*.exe);;All files(*.*)"));

    pathName = QFileDialog::getExistingDirectory(this, QStringLiteral("设置路径"),
                                            "D:/", QFileDialog::ShowDirsOnly);

    qDebug() << pathName;


    if(!pathName.length()) {
        QMessageBox::critical(this, "Error", QStringLiteral("未设置有效路径！"), QStringLiteral("确定"));
        return;
    }


    QFile file(QDir::currentPath() + "/PMS_data/path.corgi");

    if(!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QMessageBox::critical(this, "Error", QStringLiteral("文件打开失败！"), QStringLiteral("确定"));
        return;
    }


    QVector<QStringList> settings_info;

    QTextStream in(&file);
    QString line = in.readLine();


    while(!line.isNull()) {
        QStringList strList = line.split("->");

        settings_info.push_back(strList);

        line = in.readLine();

    }

    file.close();

    if(!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        QMessageBox::critical(this, "Error", QStringLiteral("文件打开失败！"), QStringLiteral("确定"));
        return;
    }



    QTextStream out(&file);





    for(auto iter = settings_info.begin(); iter != settings_info.end(); ++ iter) {

        auto curr_setting = *iter;
        if(curr_setting[0] == "Music_Path") curr_setting[1] = pathName + "/";

        out << curr_setting[0] << "->" << curr_setting[1] << '\n';
    }

    file.close();

    QMessageBox::information(this, QStringLiteral("消息"), QStringLiteral("设置成功！"), QStringLiteral("确定"));

    musicPath = pathName + "/";

    QDir dir(pathName);


    QStringList strFileList, strNameList;

    QStringList filters;

    filters << QString("*.mp3");

    dir.setNameFilters(filters);

    QDirIterator iter(dir, QDirIterator::Subdirectories);

    while(iter.hasNext()) {

        iter.next();

        QFileInfo info = iter.fileInfo();

        if(info.isFile()) strFileList.append(info.absoluteFilePath()), strNameList.append(info.baseName());


    }


    ui->listWidget->clear();

    currMusicArray.clear();

    for(auto it = strNameList.begin(); it != strNameList.end(); ++it)
        qDebug() << *it, ui->listWidget->addItem(*it), currMusicArray.push_back(*it);




}

void MusicConfig::btn_mode_slot() {

    if(!QString::compare(ui->btn_mode->text(), QStringLiteral("单次播放")))
        ui->btn_mode->setText(QStringLiteral("单曲循环")), musicState = QStringLiteral("单曲循环");
    else if(!QString::compare(ui->btn_mode->text(), QStringLiteral("单曲循环")))
        ui->btn_mode->setText(QStringLiteral("随机播放")), musicState = QStringLiteral("随机播放");
    else ui->btn_mode->setText(QStringLiteral("单次播放")), musicState = QStringLiteral("单次播放");



    qDebug() << musicState;

}

MusicConfig::~MusicConfig()
{
    delete ui;
}
